package com.abe.view;

import android.animation.ObjectAnimator;
import android.animation.ValueAnimator;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.drawable.ColorDrawable;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.animation.LinearInterpolator;
import android.widget.FrameLayout;

import com.abe.strengthtrainer.R;
import com.abe.utils.NormalUtils;
import com.abe.utils.ThreadPoolUtils;

/**
 * @see 如在xml中配置参数，可直接启动；
 * @see 重要参数：paintWidth（px） 轨道宽度；paintColor（int）轨道颜色；preparaTime（ms）
 *      等待时间；pushTime（ms） 推举时间；keepMaxTime（ms） 最大保持时间；returnTime（ms）
 *      回撤时间；screenMoveTime（ms） 屏幕整体移动一次时间
 */
@SuppressLint("DrawAllocation")
public class MoveAnimCurveView extends FrameLayout implements Runnable {
	/** 响应view的UI线程操作 */
	public interface CurveControl {
		/** 启动 */
		void callStartMove();

		/** 重启 */
		void callRestartMove();

		/** 停止 */
		void callStopMove();
	}

	private boolean isRun = false;
	private CurveControl callBack;

	protected Context mContext;
	protected CustomCurveView mcv_01;
	protected CustomCurveView mcv_02;
	protected CircleImageView cbv;
	protected ObjectAnimator animator_curve_01;
	protected ObjectAnimator animator_curve_02;
	protected ObjectAnimator animator_ball;
	/** 小球动画时间 */
	protected int ballRefreshRate = 20;

	/*************************************/
	/** view高度 */
	protected float mHeight;
	/** view宽度 */
	protected float mWitdh;
	/** 画笔宽 */
	private int paintWidth;
	/** 画笔颜色 */
	private int paintColor;
	/******** 小球相关 ********/
	private float oldBallCenterY;
	private float currentBallCenterY;
	private float ballMaxHeight = 0;
	private float ballMinHeight = 0;
	/** 小球直径 */
	private float ballWidth = 0;
	/** 小球颜色 */
	private int positionBallColor;
	/***************** 时间相关 ******************/
	/** 等待： 一组锻炼的开始的准备时间 */
	private int preparaTime = 0;
	/** 推举：开始位置至最大幅度时间 */
	private int pushTime = 0;
	/** 保持：最高位置保持时间 */
	private int keepMaxTime = 0;
	/** 回撤：最大幅度至开始位置时间 */
	private int returnTime = 0;
	/** 屏幕横向平移时间 */
	private int screenMoveTime;

	public MoveAnimCurveView(Context context) {
		this(context, null);
	}

	public MoveAnimCurveView(Context context, AttributeSet attrs) {
		this(context, attrs, 0);
	}

	public MoveAnimCurveView(Context context, AttributeSet attrs,
			int defStyleAttr) {
		super(context, attrs, defStyleAttr);
		initCustomParam(context, attrs, defStyleAttr);
		mContext = context;
		initView();
	}

	/** 初始化自定义View */
	private void initView() {
		LayoutInflater inflater = (LayoutInflater) mContext
				.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		inflater.inflate(R.layout.view_st_move_anim_curve, this);
		if (!isInEditMode()) {
			cbv = (CircleImageView) findViewById(R.id.macv_image_ball);
			cbv.setImageDrawable(new ColorDrawable(positionBallColor));
			/** 自定义曲线 */
			mcv_01 = (CustomCurveView) findViewById(R.id.mcv_01);
			mcv_02 = (CustomCurveView) findViewById(R.id.mcv_02);
			mcv_01.setScreenNum(2);
			mcv_02.setScreenNum(1);
		}
	}

	/** xml配置参数初始化 */
	private void initCustomParam(Context context, AttributeSet attrs,
			int defStyleAttr) {
		/**
		 * 获得我们所定义的自定义样式属性
		 */
		TypedArray typedArray = context.getTheme().obtainStyledAttributes(
				attrs, R.styleable.MoveAnimCurveView, defStyleAttr, 0);
		int n = typedArray.getIndexCount();
		for (int i = 0; i < n; i++) {
			int attr = typedArray.getIndex(i);
			switch (attr) {
			case R.styleable.MoveAnimCurveView_paintColor:
				/** 操场主色 */
				paintColor = typedArray.getColor(attr,
						getResources().getColor(R.color.app_theme_color));
				break;
			case R.styleable.MoveAnimCurveView_paintWidth:
				/** 画笔宽度,并进行适配 */
				paintWidth = (int) (NormalUtils.getScale(context) * typedArray
						.getDimensionPixelSize(attr, 2));
				/** 小球为画笔3/4 */
				ballWidth = paintWidth * 3 / 4;
				break;
			case R.styleable.MoveAnimCurveView_positionBallColor:
				/** 位置小球颜色 */
				positionBallColor = typedArray.getColor(attr, getResources()
						.getColor(R.color.white));
				break;
			case R.styleable.MoveAnimCurveView_preparaTime:
				preparaTime = typedArray.getInteger(attr, 0);
				break;
			case R.styleable.MoveAnimCurveView_pushTime:
				pushTime = typedArray.getInteger(attr, 0);
				break;
			case R.styleable.MoveAnimCurveView_keepMaxTime:
				keepMaxTime = typedArray.getInteger(attr, 0);
				break;
			case R.styleable.MoveAnimCurveView_returnTime:
				returnTime = typedArray.getInteger(attr, 0);
				break;
			case R.styleable.MoveAnimCurveView_screenMoveTime:
				screenMoveTime = typedArray.getInteger(attr, 0);
				break;
			}
		}
		typedArray.recycle();
	}

	@Override
	public void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
		super.onMeasure(widthMeasureSpec, heightMeasureSpec);
		mHeight = this.getMeasuredHeight();
		mWitdh = this.getMeasuredWidth();
		currentBallCenterY = 0;
		oldBallCenterY = currentBallCenterY;
		ballMaxHeight = (float) ballWidth / (float) 2;
		ballMinHeight = (float) mHeight - (float) ballWidth / (float) 2;
	}

	/** 重启 */
	public void restartMove() {
		/** 停止 */
		stopMove();
		/** 启动 */
		callBack.callStartMove();
	}

	/** 停止 */
	public void stopMove() {
		isRun = false;
		/** 轨道停止动画 */
		post(new Runnable() {

			@Override
			public void run() {
				animator_curve_01.cancel();
				animator_curve_02.cancel();
			}
		});
	}

	@Override
	public void run() {
		if (isRun) {
			return;
		}
		/** 启动 */
		isRun = true;
		runBackCurveView();
		runBallView();
	}

	/** 绘制轨道 */
	private void runBackCurveView() {
		runCurveView(mcv_02);
		runCurveView(mcv_01);
		/** 平移速度 */
		float moveSpeed = mWitdh / screenMoveTime;
		float animMoveDis = moveSpeed * mcv_01.getGroupTime();
		/** 平移动画 */
		animator_curve_01 = ObjectAnimator.ofFloat(mcv_01, "translationX", 0,
				-animMoveDis);
		animator_curve_01.setInterpolator(new LinearInterpolator());
		animator_curve_01.setDuration(mcv_01.getGroupTime());
		animator_curve_01.setRepeatCount(ValueAnimator.INFINITE);
		animator_curve_01.setRepeatMode(ValueAnimator.INFINITE);
		animator_curve_02 = ObjectAnimator.ofFloat(mcv_02, "translationX", 0,
				-animMoveDis);
		animator_curve_02.setInterpolator(new LinearInterpolator());
		animator_curve_02.setDuration(mcv_02.getGroupTime());
		animator_curve_02.setRepeatCount(ValueAnimator.INFINITE);
		animator_curve_02.setRepeatMode(ValueAnimator.INFINITE);
		post(new Runnable() {

			@Override
			public void run() {
				animator_curve_01.start();
				animator_curve_02.start();
			}
		});
	}

	/** 绘制小球 */
	private void runBallView() {
		post(new Runnable() {

			@Override
			public void run() {
				/** 设置小球参数 */
				FrameLayout.LayoutParams params = (LayoutParams) cbv
						.getLayoutParams();
				params.width = (int) ballWidth;
				params.height = (int) ballWidth;
				cbv.setLayoutParams(params);
			}
		});

		while (isRun) {
			if (oldBallCenterY != currentBallCenterY) {
				animator_ball = ObjectAnimator.ofFloat(cbv, "translationY",
						oldBallCenterY, currentBallCenterY);
				/** 设置插值器，渐快 */
				animator_ball.setInterpolator(new LinearInterpolator());
				animator_ball.setDuration(ballRefreshRate);
				post(new Runnable() {

					@Override
					public void run() {
						animator_ball.start();
					}
				});
				oldBallCenterY = currentBallCenterY;
				try {
					Thread.sleep(ballRefreshRate);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
		}
	}

	/** 设置轨道参数 */
	private void runCurveView(CustomCurveView mcv) {
		mcv.setScreenMoveTime(screenMoveTime);
		mcv.setPaintWidth(paintWidth);
		mcv.setPaintColor(paintColor);
		mcv.setPreparaTime(preparaTime);
		mcv.setPushTime(pushTime);
		mcv.setKeepMaxTime(keepMaxTime);
		mcv.setReturnTime(returnTime);
		ThreadPoolUtils.execute(mcv);
	}

	/** 设置小球直径 */
	public void setBallWidth(float ballWidth) {
		this.ballWidth = ballWidth;
	}

	/** 设置小球Y坐标 */
	public void setBallCenterY(float ballCenterY) {
		currentBallCenterY = ballCenterY;
	}

	public boolean isRun() {
		return isRun;
	}

	/** 获取最小Y坐标 */
	public float getMinHeight() {
		return mcv_01.getMinHeight();
	}

	/** 获取最大Y坐标 */
	public float getMaxHeight() {
		return mcv_01.getMaxHeight();
	}

	public void setCallBack(CurveControl callBack) {
		this.callBack = callBack;
	}

	public void setPaintWidth(int paintWidth) {
		this.paintWidth = paintWidth;
	}

	public void setPaintColor(int paintColor) {
		this.paintColor = paintColor;
	}

	public void setPositionBallColor(int positionBallColor) {
		this.positionBallColor = positionBallColor;
	}

	public void setPreparaTime(int preparaTime) {
		this.preparaTime = preparaTime;
	}

	public void setPushTime(int pushTime) {
		this.pushTime = pushTime;
	}

	public void setKeepMaxTime(int keepMaxTime) {
		this.keepMaxTime = keepMaxTime;
	}

	public void setReturnTime(int returnTime) {
		this.returnTime = returnTime;
	}

	public void setScreenMoveTime(int screenMoveTime) {
		this.screenMoveTime = screenMoveTime;
	}

	/**
	 * 转换为屏幕小球位置
	 * 
	 * @param ballHeight
	 *            实时高度
	 * */
	public void setBallScreenHeight(float scaleHeight) {
		setBallCenterY((ballMaxHeight - ballMinHeight) * scaleHeight);
	}
}
